package com.dudu.controller;

import java.io.File;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;

import com.dudu.access.YonYouUtil;
import com.dudu.bean.AccountBean;
import com.dudu.bean.AppExtendBean;
import com.dudu.bean.ResponseSendVoiceBean;
import com.dudu.enumeration.AbilityTypeEnum;
import com.dudu.service.IAccountExtendService;
import com.dudu.service.IAppExtendService;
import com.dudu.service.IAudeoNoticeService;
import com.dudu.service.ICheckValidityService;
import com.dudu.service.ILogService;
import com.dudu.service.IOperationPlatformService;
import com.dudu.service.IVoiceNoticeService;
import com.dudu.service.WavTTSSynthesizeCallback;
import com.dudu.service.impl.AccountExtendServiceImpl;
import com.dudu.service.impl.AppExtendServiceImpl;
import com.dudu.service.impl.AudeoNoticeServiceImpl;
import com.dudu.service.impl.CheckValidityServiceImpl;
import com.dudu.service.impl.LogService;
import com.dudu.service.impl.OperationPlatformServiceImpl;
import com.dudu.service.impl.VoiceNoticeServiceImpl;
import com.dudu.utils.AbstractTTSSynthesizeCallback;
import com.dudu.utils.DateUtils;
import com.dudu.utils.PhoneUtils;
import com.dudu.utils.TTSUtils;
import com.dudu.utils.VoiceUtil;

import core.CoreService;

/**
 * 文字语音短信开放接口v4.0
 * 
 * @author 危东
 * @date 2016-5-10
 */
public class OpenAbilityVOICEController extends CoreService implements IOpenAbilityVOICEController {

    // ims能力调用
    private IVoiceNoticeService voiceNoticeService = new VoiceNoticeServiceImpl();

    private ILogService logService = new LogService();
    // 被叫人数限定
    private int calleeNum = 51;
    // app扩展信息操作
    private IAppExtendService appExtendService = new AppExtendServiceImpl();
    private IAccountExtendService accountExtendService = new AccountExtendServiceImpl();
    // 验证信息类
    private ICheckValidityService checkValidityService = new CheckValidityServiceImpl();
    // 运营平台相关操作
    private IOperationPlatformService operationPlatformService = new OperationPlatformServiceImpl();

    private static long FILE_MAXLENGTH = 10 * 1024 * 1024;

    // 语音信息能力调用
    private IAudeoNoticeService audeoNoticeService = new AudeoNoticeServiceImpl();

    /**
     * 发起文字语音短信（旧版）
     * 
     * @return
     */
    @Override
    public String sendVoiceNotice() {
	CoreService.log.info("load sendVoiceNotice 发起文字语音短信");
	long begin = Calendar.getInstance().getTimeInMillis();
	// 接口请求参数
	List<String[]> checkParamlist = new ArrayList<String[]>();
	// app_key应用标识
	String app_key = this.getRequest().getParameter("app_key");
	String[] app_keyStr = { "app_key", app_key, "50", "0", "str" };
	checkParamlist.add(app_keyStr);
	// cust_account账号标识
	String cust_account = this.getRequest().getParameter("cust_account");
	String[] cust_accountStr = { "cust_account", cust_account, "50", "0", "str" };
	checkParamlist.add(cust_accountStr);
	// 时间戳
	String timestamp = this.getRequest().getParameter("timestamp");
	String[] timestampStr = { "timestamp", timestamp, "20", "0", "str" };
	checkParamlist.add(timestampStr);
	// 认证码
	String sign = this.getRequest().getParameter("sign");
	String[] signStr = { "sign", sign, "50", "0", "str" };
	checkParamlist.add(signStr);
	// 发起语音短信的用户ID
	String ext_terminalCode = this.getRequest().getParameter("ext_terminalCode");
	String[] ext_terminalCodeStr = { "ext_terminalCode", ext_terminalCode, "50", "0", "str" };
	checkParamlist.add(ext_terminalCodeStr);
	// 预约发起短信时间
	String schedule_send_time = this.getRequest().getParameter("schedule_send_time");
	String[] schedule_send_timeStr = { "schedule_send_time", schedule_send_time, "50", "1", "date" };
	checkParamlist.add(schedule_send_timeStr);
	// 主叫号码
	String caller = this.getRequest().getParameter("caller");
	String[] callerStr = { "caller", caller, "20", "0", "str" };
	checkParamlist.add(callerStr);
	// 被叫号码：以‘,’分割
	String called = this.getRequest().getParameter("called");
	String[] calledStr = { "called", called, "1000", "0", "str" };
	checkParamlist.add(calledStr);
	// 被叫号码，json数组[{"phone":"17001090122","msg_id":"49810560379194247739837403838602"}]
	String calledData = this.getRequest().getParameter("called_data");
	String[] called_dataStr = { "calledData", calledData, "1000", "1", "str" };
	checkParamlist.add(called_dataStr);
	boolean isCalledDataNull = true;
	if (StringUtils.isNotBlank(calledData)) {
	    isCalledDataNull = false;
	} else {
	    calledData = "";
	}
	// 语音通信预约后，通信发起sessionid接收地址
	String push_url = this.getRequest().getParameter("push_url");
	String[] push_urlStr = { "push_url", push_url, "1000", "1", "str" };
	checkParamlist.add(push_urlStr);
	if (StringUtils.isBlank(push_url)) {
	    push_url = "";
	}
	// 前导音
	String tts_content = this.getRequest().getParameter("tts_content");
	String[] tts_contentStr = { "tts_content", tts_content, "50", "1", "str" };
	checkParamlist.add(tts_contentStr);
	// 判断如果前导音为空未收到参数，则处理为空字符串
	if (StringUtils.isBlank(tts_content)) {
	    tts_content = "";
	}
	// ISV自行定义使用哪个号码发起通话
	String pool_ability_id = this.getRequest().getParameter("pool_ability_id");
	String[] pool_ability_idStr = { "pool_ability_id", pool_ability_id, "20", "1", "str" };
	checkParamlist.add(pool_ability_idStr);
	// 判断如果号码参数为空未收到参数，则处理为空字符串
	if (StringUtils.isBlank(pool_ability_id)) {
	    pool_ability_id = "";
	}
	// 强制使用平台号码(值为1时，强制使用平台号码发起)
	String usePlatNbr = this.getRequest().getParameter("usePlatNbr");
	String[] usePlatNbrStr = { "usePlatNbr", usePlatNbr, "20", "1", "str" };
	checkParamlist.add(usePlatNbrStr);
	if (StringUtils.isBlank(usePlatNbr) || !"1".equals(usePlatNbr)) { // 不为1时不强制使用平台号
	    usePlatNbr = "";
	}
	// 是否为一批次
	String batch_number = this.getRequest().getParameter("batch_number");
	String[] batch_numberStr = { "batch_number", batch_number, "100", "1", "str" };
	checkParamlist.add(batch_numberStr);
	if (StringUtils.isBlank(batch_number)) {
	    batch_number = "";
	}
	// 语音通知类型：VOICE70，70字文字语音通知；VOICE140，140字文字语音通知
	String voice_type = this.getRequest().getParameter("voice_type"); // 可以为空
	String[] voice_typeStr = { "voice_type", voice_type, "10", "1", "str" };
	checkParamlist.add(voice_typeStr);
	if (StringUtils.isBlank(voice_type)) {
	    voice_type = "";
	}

	String content = "";
	// 适配jsonp
	String callback = this.getRequest().getParameter("callback");
	JSONObject object = null;
	try {
	    content = URLDecoder.decode(this.getRequest().getParameter("content"), "UTF-8");
	    String[] contentStr = { "content", content, "1000", "0", "str" };
	    checkParamlist.add(contentStr);
	    object = this.checkParams(checkParamlist);
	    if (null == object) {
		object = new JSONObject();
		JSONArray calledJsonArray = new JSONArray();
		if (!isCalledDataNull) {
		    calledJsonArray = JSONArray.fromObject(calledData);
		    called = VoiceUtil.parsePhone(calledJsonArray);
		}
		// 判断手机号码是否正确，过滤外国号码等
		if (PhoneUtils.filterIssueNumber(caller) && PhoneUtils.filterIssueNumber(called)) {
		    // 处理重复的电话号码
		    if (isCalledDataNull) {
			called = PhoneUtils.phoneNumDereplication(called);
		    }
		    // 被叫人数限定
		    String[] calleeStr = called.split(",");
		    if (calleeStr != null && calleeStr.length < calleeNum) {
			// 查询应用信息
			AppExtendBean appExtendBean = appExtendService.queryAppExtendByIdentify(app_key);
			// 判断app信息是否为空
			if (appExtendBean != null) {
			    // 根据cust_account查询账号信息
			    AccountBean accountBean = accountExtendService.queryAccountDetailByCustAccount(cust_account);
			    // 判断账号信息是否找到
			    if (accountBean != null) {
				// 验证秘钥信息
				if (checkValidityService.toolsCheckSign(cust_account, accountBean.getKey_private(), timestamp, sign)) {
				    // 获取语音短信能力类型标识
				    String abilityType = AbilityTypeEnum.VOICE.getKey();
				    abilityType = VoiceUtil.changeAbilityTypeByVoiceType(abilityType, voice_type, "tts");
				    // 到运营平台验证账号相关信息--判断是否可以通话
				    if (operationPlatformService.platformAuthentication(object, appExtendBean, accountBean, abilityType)) {
					// 发起留言
					object = voiceNoticeService.sendVoiceNotice(appExtendBean, accountBean, ext_terminalCode, caller, called,
						content.replaceAll("\r|\n|\t", ""), schedule_send_time, push_url, tts_content, pool_ability_id, batch_number, usePlatNbr,
						calledJsonArray, abilityType);
				    } else {
					object.put("result", "-1");
					object.put("code", object.getString("code"));
					object.put("describe", object.getString("describe"));
				    }
				} else {
				    object.put("result", "-1");
				    object.put("describe", "参数sign错误");
				    object.put("code", "0001");
				}
			    } else {
				object.put("result", "-1");
				object.put("describe", "计费账号不存在");
				object.put("code", "0002");
			    }
			} else {
			    object.put("result", "-1");
			    object.put("describe", "请使用正确的应用标识");
			    object.put("code", "0007");
			}
		    } else {
			object.put("result", "-1");
			object.put("describe", "单次提交的手机号码数量不能超过" + calleeNum + "个");
			object.put("code", "0502");
		    }
		} else {
		    object.put("result", "-1");
		    object.put("describe", "号码格式错误");
		    object.put("code", "0004");
		}
	    }
	} catch (Exception e) {
	    log.info("********文字短信留言失败**********" + e);
	    object = new JSONObject();
	    object.put("result", "-1");
	    object.put("describe", "语音通知异常");
	    object.put("errorMsg", e.getMessage());
	    object.put("code", "0501");
	}

	// 计算结束时间
	double end = Calendar.getInstance().getTimeInMillis();
	// 计算发起接口道调用完毕所用的时间
	double during = Double.valueOf((end - begin)) / 1000;
	// 拼写写入日志内容
	String request_msg = "ext_terminalCode:" + ext_terminalCode + "|app_key:" + app_key + "|cust_account:" + cust_account + "|caller:" + caller + "|called:"
		+ (called.length() > 200 ? called.substring(0, 200) : called) + "|calledData:" + (calledData.length() > 200 ? calledData.substring(0, 200) : calledData)
		+ "|timestamp:" + timestamp + "|sign:" + sign + "|schedule_send_time:" + schedule_send_time + "|content:" + content + "|pool_ability_id:" + pool_ability_id
		+ "|usePlatNbr:" + usePlatNbr + "batch_number:" + batch_number + "|voice_type:" + voice_type + "|push_url:" + push_url + "|tts_content:" + tts_content;
	this.logService.logInterface(during, "sendVoiceNoticeV4", request_msg.length() > 500 ? request_msg.substring(0, 500) : request_msg,
		object.toString().length() > 200 ? object.toString().substring(0, 200) : object.toString(), object.getString("result").length() > 200 ? object.getString("result")
			.substring(0, 200) : object.getString("result"), DateUtils.getCurrentTime(), this.getRequest().getRemoteAddr(), caller);

	String data = "";
	object.remove("errorMsg");
	if (StringUtils.isNotBlank(callback)) {
	    data = callback + "(" + object.toString() + ")";
	} else {
	    data = object.toString();
	}
	return returnData(data);
    }

    /**
     * 重发语音通知（旧版）
     * 
     * @return
     */
    @Override
    public String sendVoiceNoticeLet() {
	log.info("load sendVoiceNoticeLet 重发语音通知");
	long begin = Calendar.getInstance().getTimeInMillis();
	// 接口请求参数
	List<String[]> checkParamlist = new ArrayList<String[]>();
	// app_key应用标识
	String app_key = this.getRequest().getParameter("app_key");
	String[] app_keyStr = { "app_key", app_key, "50", "0", "str" };
	checkParamlist.add(app_keyStr);
	// cust_account账号标识
	String cust_account = this.getRequest().getParameter("cust_account");
	String[] cust_accountStr = { "cust_account", cust_account, "50", "0", "str" };
	checkParamlist.add(cust_accountStr);
	// 时间戳
	String timestamp = this.getRequest().getParameter("timestamp");
	String[] timestampStr = { "timestamp", timestamp, "20", "0", "str" };
	checkParamlist.add(timestampStr);
	// 认证码
	String sign = this.getRequest().getParameter("sign");
	String[] signStr = { "sign", sign, "50", "0", "str" };
	checkParamlist.add(signStr);
	// 发起语音短信的用户ID
	String ext_terminalCode = this.getRequest().getParameter("ext_terminalCode");
	String[] ext_terminalCodeStr = { "ext_terminalCode", ext_terminalCode, "50", "0", "str" };
	checkParamlist.add(ext_terminalCodeStr);
	// 主叫号码
	String caller = this.getRequest().getParameter("caller");
	String[] callerStr = { "caller", caller, "20", "0", "str" };
	checkParamlist.add(callerStr);
	// 被叫号码：以‘,’分割
	String called = this.getRequest().getParameter("called");
	String[] calledStr = { "called", called, "1000", "0", "str" };
	checkParamlist.add(calledStr);
	// 被叫号码，json数组[{"phone":"17001090122","msg_id":"49810560379194247739837403838602"}]
	String calledData = this.getRequest().getParameter("called_data");
	String[] called_dataStr = { "calledData", calledData, "600", "1", "str" };
	checkParamlist.add(called_dataStr);
	boolean isCalledDataNull = true;
	if (StringUtils.isNotBlank(calledData)) {
	    isCalledDataNull = false;
	} else {
	    calledData = "";
	}
	// 预约发起短信时间
	String schedule_send_time = this.getRequest().getParameter("schedule_send_time");
	String[] schedule_send_timeStr = { "schedule_send_time", schedule_send_time, "50", "1", "date" };
	checkParamlist.add(schedule_send_timeStr);
	// 重发的信息的原始id
	String voice_id = this.getRequest().getParameter("voice_id");
	String[] voice_idStr = { "voice_id", voice_id, "50", "1", "str" };
	checkParamlist.add(voice_idStr);
	// 语音通信预约后，通信发起sessionid接收地址
	String push_url = this.getRequest().getParameter("push_url");
	String[] push_urlStr = { "push_url", push_url, "1000", "1", "str" };
	checkParamlist.add(push_urlStr);
	if (StringUtils.isBlank(push_url)) {
	    push_url = "";
	}
	// 前导音
	String tts_content = this.getRequest().getParameter("tts_content");
	String[] tts_contentStr = { "tts_content", tts_content, "50", "1", "str" };
	checkParamlist.add(tts_contentStr);
	// 判断如果前导音为空未收到参数，则处理为-1，设置为-1，则使用原始语音通知
	if (StringUtils.isBlank(tts_content)) {
	    tts_content = "-1";
	}
	// ISV自行定义使用哪个号码发起通话
	String pool_ability_id = this.getRequest().getParameter("pool_ability_id");
	String[] pool_ability_idStr = { "pool_ability_id", pool_ability_id, "20", "1", "str" };
	checkParamlist.add(pool_ability_idStr);
	// 判断如果号码参数为空未收到参数，则处理为空字符串
	if (StringUtils.isBlank(pool_ability_id)) {
	    pool_ability_id = "";
	}
	// 强制使用平台号码(值为1时，强制使用平台号码发起)
	String usePlatNbr = this.getRequest().getParameter("usePlatNbr");
	String[] usePlatNbrStr = { "usePlatNbr", usePlatNbr, "20", "1", "str" };
	checkParamlist.add(usePlatNbrStr);
	if (StringUtils.isBlank(usePlatNbr) || !"1".equals(usePlatNbr)) { // 不为1时不强制使用平台号
	    usePlatNbr = "";
	}
	// 是否为一批次
	String batch_number = this.getRequest().getParameter("batch_number");
	String[] batch_numberStr = { "batch_number", batch_number, "100", "1", "str" };
	checkParamlist.add(batch_numberStr);
	if (StringUtils.isBlank(batch_number)) {
	    batch_number = "";
	}
	// 语音通知类型：VOICE70，70字文字语音通知；VOICE140，140字文字语音通知
	String voice_type = this.getRequest().getParameter("voice_type"); // 可以为空
	String[] voice_typeStr = { "voice_type", voice_type, "10", "1", "str" };
	checkParamlist.add(voice_typeStr);
	if (StringUtils.isBlank(voice_type)) {
	    voice_type = "";
	}
	// 适配jsonp
	String callback = this.getRequest().getParameter("callback");
	JSONObject object = null;
	try {
	    object = this.checkParams(checkParamlist);
	    if (null == object) {
		object = new JSONObject();
		JSONArray calledJsonArray = new JSONArray();
		if (!isCalledDataNull) {
		    calledJsonArray = JSONArray.fromObject(calledData);
		    called = VoiceUtil.parsePhone(calledJsonArray);
		} else {
		    // 处理重复的电话号码
		    called = PhoneUtils.phoneNumDereplication(called);
		}
		// 被叫人数限定
		String[] calleeStr = called.split(",");
		if (calleeStr != null && calleeStr.length < calleeNum) {
		    // 查询应用信息
		    AppExtendBean appExtendBean = appExtendService.queryAppExtendByIdentify(app_key);
		    // 判断app信息是否为空
		    if (appExtendBean != null) {
			// 根据cust_account查询账号信息
			AccountBean accountBean = accountExtendService.queryAccountDetailByCustAccount(cust_account);
			// 判断账号信息是否找到
			if (accountBean != null) {
			    // 验证秘钥信息
			    if (checkValidityService.toolsCheckSign(cust_account, accountBean.getKey_private(), timestamp, sign)) {
				// 获取语音短信能力类型标识
				String abilityType = AbilityTypeEnum.VOICE.getKey();
				abilityType = VoiceUtil.changeAbilityTypeByVoiceType(abilityType, voice_type, "tts");
				// 到运营平台验证账号相关信息--判断是否可以通话
				if (operationPlatformService.platformAuthentication(object, appExtendBean, accountBean, abilityType)) {
				    // 重新发起IMS文字语音信息
				    object = voiceNoticeService.sendVoiceNoticeLet(appExtendBean, accountBean, ext_terminalCode, voice_id, caller, called, schedule_send_time,
					    push_url, tts_content, pool_ability_id, batch_number, usePlatNbr, calledJsonArray, abilityType);
				} else {
				    object.put("result", "-1");
				    object.put("code", object.getString("code"));
				    object.put("describe", object.getString("describe"));
				}
			    } else {
				object.put("result", "-1");
				object.put("describe", "参数sign错误");
				object.put("code", "0001");
			    }
			} else {
			    object.put("result", "-1");
			    object.put("describe", "计费账号不存在");
			    object.put("code", "0002");
			}
		    } else {
			object.put("result", "-1");
			object.put("describe", "请使用正确的应用标识");
			object.put("code", "0007");
		    }
		} else {
		    object.put("result", "-1");
		    object.put("describe", "单次提交的手机号码数量不能超过" + calleeNum + "个");
		    object.put("code", "0502");
		}
	    }
	} catch (Exception e) {
	    log.info("********重新发起文字短信留言失败**********" + e);
	    object = new JSONObject();
	    object.put("result", "-1");
	    object.put("describe", "语音通知异常");
	    object.put("errorMsg", e.getMessage());
	    object.put("code", "0501");
	}

	// 计算结束时间
	double end = Calendar.getInstance().getTimeInMillis();
	// 计算发起接口道调用完毕所用的时间
	double during = Double.valueOf((end - begin)) / 1000;
	// 拼写写入日志内容
	String request_msg = "ext_terminalCode:" + ext_terminalCode + "|app_key:" + app_key + "|cust_account:" + cust_account + "|caller:" + caller + "|called:"
		+ (called.length() > 200 ? called.substring(0, 200) : called) + "|calledData:" + (calledData.length() > 200 ? calledData.substring(0, 200) : calledData)
		+ "|timestamp:" + timestamp + "|sign:" + sign + "|schedule_send_time:" + schedule_send_time + "|voice_id:" + voice_id + "|pool_ability_id:" + pool_ability_id
		+ "usePlatNbr:" + usePlatNbr + "batch_number:" + batch_number + "|voice_type:" + voice_type + "|push_url:" + push_url + "|tts_content:" + tts_content;
	this.logService.logInterface(during, "sendVoiceNoticeLetV4", request_msg.length() > 500 ? request_msg.substring(0, 500) : request_msg,
		object.toString().length() > 200 ? object.toString().substring(0, 200) : object.toString(), object.getString("result").length() > 200 ? object.getString("result")
			.substring(0, 200) : object.getString("result"), DateUtils.getCurrentTime(), this.getRequest().getRemoteAddr(), caller);

	String data = "";
	object.remove("errorMsg");
	if (StringUtils.isNotBlank(callback)) {
	    data = callback + "(" + object.toString() + ")";
	} else {
	    data = object.toString();
	}

	return returnData(data);
    }

    /**
     * 重发语音通知（只用于赵希的监控）
     * 
     * @return
     */
    public String sendVoiceNoticeByVoiceId() {
	log.info("load sendVoiceNoticeLet 根据之前上传的，已经处理好的语音，重新发起通话");
	long begin = Calendar.getInstance().getTimeInMillis();
	// app_key应用标识
	String app_key = this.getRequest().getParameter("app_key");
	// cust_account账号标识
	String cust_account = this.getRequest().getParameter("cust_account");
	// 发起语音短信的用户ID
	String ext_terminalCode = this.getRequest().getParameter("ext_terminalCode");
	// 被叫号码：以‘,’分割
	String called = this.getRequest().getParameter("called");
	// 被叫号码，json数组[{"phone":"17001090122","msg_id":"49810560379194247739837403838602"}]
	String calledData = this.getRequest().getParameter("called_data");
	boolean isCalledDataNull = true;
	if (StringUtils.isNotBlank(calledData)) {
	    isCalledDataNull = false;
	} else {
	    calledData = "";
	}
	// 重发的信息的原始id
	String voice_id = this.getRequest().getParameter("voice_id");
	// 时间戳
	String timestamp = this.getRequest().getParameter("timestamp");
	// 认证码
	String sign = this.getRequest().getParameter("sign");
	// 语音通信预约后，通信发起sessionid接收地址
	String push_url = this.getRequest().getParameter("push_url");
	if (StringUtils.isBlank(push_url)) {
	    push_url = "";
	}
	// 适配jsonp
	String callback = this.getRequest().getParameter("callback");
	JSONObject object = new JSONObject();
	try {
	    JSONArray calledJsonArray = new JSONArray();
	    if (!isCalledDataNull) {
		calledJsonArray = JSONArray.fromObject(calledData);
		called = VoiceUtil.parsePhone(calledJsonArray);
	    } else {
		// 处理重复的电话号码
		called = PhoneUtils.phoneNumDereplication(called);
	    }
	    // 被叫人数限定
	    String[] calleeStr = called.split(",");
	    if (calleeStr != null && calleeStr.length < calleeNum) {
		// 查询应用信息
		AppExtendBean appExtendBean = appExtendService.queryAppExtendByIdentify(app_key);
		// 判断app信息是否为空
		if (appExtendBean != null) {
		    // 根据cust_account查询账号信息
		    AccountBean accountBean = accountExtendService.queryAccountDetailByCustAccount(cust_account);
		    // 判断账号信息是否找到
		    if (accountBean != null) {
			// 验证秘钥信息
			if (checkValidityService.toolsCheckSign(cust_account, accountBean.getKey_private(), timestamp, sign)) {
			    // 获取语音短信能力类型标识
			    String abilityType = AbilityTypeEnum.VOICE.getKey();
			    // 到运营平台验证账号相关信息--判断是否可以通话
			    if (operationPlatformService.platformAuthentication(object, appExtendBean, accountBean, abilityType)) {
				// 重新发起IMS文字语音信息
				object = voiceNoticeService.sendVoiceNoticeByVoiceId(app_key, cust_account, voice_id, called, ext_terminalCode, push_url, calledJsonArray);
			    } else {
				object.put("result", "-1");
				object.put("code", object.getString("code"));
				object.put("describe", object.getString("describe"));
			    }
			} else {
			    object.put("result", "-1");
			    object.put("describe", "参数sign错误");
			    object.put("code", "0001");
			}
		    } else {
			object.put("result", "-1");
			object.put("describe", "计费账号不存在");
			object.put("code", "0002");
		    }
		} else {
		    object.put("result", "-1");
		    object.put("describe", "请使用正确的应用标识");
		    object.put("code", "0007");
		}
	    } else {
		object.put("result", "-1");
		object.put("describe", "单次提交的手机号码数量不能超过" + calleeNum + "个");
		object.put("code", "0502");
	    }
	} catch (Exception e) {
	    log.info("********重新发起文字短信留言失败**********" + e);
	    object.put("result", "-1");
	    object.put("describe", "语音通知异常");
	    object.put("errorMsg", e.getMessage());
	    object.put("code", "0501");
	}

	// 计算结束时间
	double end = Calendar.getInstance().getTimeInMillis();
	// 计算发起接口道调用完毕所用的时间
	double during = Double.valueOf((end - begin)) / 1000;
	// 拼写写入日志内容
	String request_msg = "ext_terminalCode:" + ext_terminalCode + "|app_key:" + app_key + "|cust_account:" + cust_account + "|called:"
		+ (called.length() > 200 ? called.substring(0, 200) : called) + "|calledData:" + (calledData.length() > 200 ? calledData.substring(0, 200) : calledData)
		+ "|timestamp:" + timestamp + "|sign:" + sign + "|voice_id:" + voice_id + "|push_url:" + push_url;
	this.logService.logInterface(during, "sendVoiceNoticeByVoiceId", request_msg.length() > 500 ? request_msg.substring(0, 500) : request_msg,
		object.toString().length() > 200 ? object.toString().substring(0, 200) : object.toString(), object.getString("result").length() > 200 ? object.getString("result")
			.substring(0, 200) : object.getString("result"), DateUtils.getCurrentTime(), this.getRequest().getRemoteAddr(), called);

	String data = "";
	object.remove("errorMsg");
	if (StringUtils.isNotBlank(callback)) {
	    data = callback + "(" + object.toString() + ")";
	} else {
	    data = object.toString();
	}

	return returnData(data);
    }

    /**
     * 取消语音通知
     * 
     * @return
     */
    public String cancelVoiceNotice() {
	log.info("load cancelVoiceNotice");
	long begin = Calendar.getInstance().getTimeInMillis();
	// 接口请求参数
	List<String[]> checkParamlist = new ArrayList<String[]>();
	// app_key应用标识
	String app_key = this.getRequest().getParameter("app_key");
	String[] app_keyStr = { "app_key", app_key, "50", "0", "str" };
	checkParamlist.add(app_keyStr);
	// cust_account账号标识
	String cust_account = this.getRequest().getParameter("cust_account");
	String[] cust_accountStr = { "cust_account", cust_account, "50", "0", "str" };
	checkParamlist.add(cust_accountStr);
	// 发起语音短信的用户ID
	String ext_terminalCode = this.getRequest().getParameter("ext_terminalCode");
	String[] ext_terminalCodeStr = { "ext_terminalCode", ext_terminalCode, "50", "0", "str" };
	checkParamlist.add(ext_terminalCodeStr);
	// 时间戳
	String timestamp = this.getRequest().getParameter("timestamp");
	String[] timestampStr = { "timestamp", timestamp, "20", "0", "str" };
	checkParamlist.add(timestampStr);
	// 认证码
	String sign = this.getRequest().getParameter("sign");
	String[] signStr = { "sign", sign, "50", "0", "str" };
	checkParamlist.add(signStr);
	// 批次号
	String batch_number = this.getRequest().getParameter("batch_number");
	String[] batch_numberStr = { "batch_number", batch_number, "100", "1", "str" };
	checkParamlist.add(batch_numberStr);
	if (StringUtils.isBlank(batch_number)) {
	    batch_number = "";
	}
	// voice_id
	String voice_id = this.getRequest().getParameter("voice_id");
	String[] voice_idStr = { "voice_id", voice_id, "50", "1", "str" };
	checkParamlist.add(voice_idStr);
	if (StringUtils.isBlank(voice_id)) {
	    voice_id = "";
	}
	String sessionId = this.getRequest().getParameter("session_id");
	String[] sessionIdStr = { "sessionId", sessionId, "50", "1", "str" };
	checkParamlist.add(sessionIdStr);
	if (StringUtils.isBlank(sessionId)) {
	    sessionId = "";
	}
	JSONObject object = null;
	try {
	    object = this.checkParams(checkParamlist);
	    if (null == object) {
		object = new JSONObject();
		// 查询应用信息
		AppExtendBean appExtendBean = appExtendService.queryAppExtendByIdentify(app_key);
		// 判断app信息是否为空
		if (appExtendBean != null) {
		    // 根据cust_account查询账号信息
		    AccountBean accountBean = accountExtendService.queryAccountDetailByCustAccount(cust_account);
		    // 判断账号信息是否找到
		    if (accountBean != null) {
			// 验证秘钥信息
			if (checkValidityService.toolsCheckSign(cust_account, accountBean.getKey_private(), timestamp, sign)) {
			    object = voiceNoticeService.cancelVoiceNotice(app_key, cust_account, voice_id, batch_number, sessionId);
			} else {
			    object.put("result", "-1");
			    object.put("describe", "参数sign错误");
			    object.put("code", "0001");
			}
		    } else {
			object.put("result", "-1");
			object.put("describe", "计费账号不存在");
			object.put("code", "0002");
		    }
		} else {
		    object.put("result", "-1");
		    object.put("describe", "请使用正确的应用标识");
		    object.put("code", "0007");
		}
	    }
	} catch (Exception e) {
	    log.info("******** 取消语音通知失败**********" + e);
	    object = new JSONObject();
	    object.put("result", "-1");
	    object.put("describe", "语音通知异常");
	    object.put("errorMsg", e.getMessage());
	    object.put("code", "0501");
	}
	// 计算结束时间
	double end = Calendar.getInstance().getTimeInMillis();
	// 计算发起接口道调用完毕所用的时间
	double during = Double.valueOf((end - begin)) / 1000;
	// 拼写写入日志内容
	String request_msg = "app_key:" + app_key + "|cust_account:" + cust_account + "|timestamp:" + timestamp + "|sign:" + sign + "|ext_terminalCode:" + ext_terminalCode
		+ "|batch_number:" + batch_number + "|voice_id:" + voice_id + "|sessionId:" + sessionId;
	this.logService.logInterface(during, "cancelVoiceNoticeV4", request_msg.length() > 500 ? request_msg.substring(0, 500) : request_msg,
		object.toString().length() > 200 ? object.toString().substring(0, 200) : object.toString(), object.getString("result").length() > 200 ? object.getString("result")
			.substring(0, 200) : object.getString("result"), DateUtils.getCurrentTime(), this.getRequest().getRemoteAddr(), "");
	object.remove("errorMsg");
	return returnData(object.toString());
    }

    /**
     * 文字转语音接口
     * 
     * @return
     */
    @Override
    public String uploadVoiceNotice() {
	log.info("load uploadVoiceNotice 文字转语音接口");
	long begin = Calendar.getInstance().getTimeInMillis();
	// 接口请求参数
	List<String[]> checkParamlist = new ArrayList<String[]>();
	// app_key应用标识
	String app_key = this.getRequest().getParameter("app_key");
	String[] app_keyStr = { "app_key", app_key, "50", "0", "str" };
	checkParamlist.add(app_keyStr);
	// cust_account账号标识
	String cust_account = this.getRequest().getParameter("cust_account");
	String[] cust_accountStr = { "cust_account", cust_account, "50", "0", "str" };
	checkParamlist.add(cust_accountStr);
	// 时间戳
	String timestamp = this.getRequest().getParameter("timestamp");
	String[] timestampStr = { "timestamp", timestamp, "20", "0", "str" };
	checkParamlist.add(timestampStr);
	// 认证码
	String sign = this.getRequest().getParameter("sign");
	String[] signStr = { "sign", sign, "50", "0", "str" };
	checkParamlist.add(signStr);
	// 上传语音短信的用户ID
	String ext_terminalCode = this.getRequest().getParameter("ext_terminalCode");
	String[] ext_terminalCodeStr = { "ext_terminalCode", ext_terminalCode, "50", "0", "str" };
	checkParamlist.add(ext_terminalCodeStr);
	// 发送语音短信的文字信息
	String content = this.getRequest().getParameter("content");
	String[] contentStr = { "content", content, "1000", "0", "str" };
	checkParamlist.add(contentStr);
	
	// 适配jsonp
	String callback = this.getRequest().getParameter("callback");
	JSONObject object = null;
	try {
	    object = this.checkParams(checkParamlist);
	    if (null == object) {
		try {
		    // 对中文编码进行处理
		    content = URLDecoder.decode(content, "UTF-8");
		} catch (Exception e1) {
		    e1.printStackTrace();
		}
		object = new JSONObject();
		// 查询应用信息
		AppExtendBean appExtendBean = appExtendService.queryAppExtendByIdentify(app_key);
		// 判断app信息是否为空
		if (appExtendBean != null) {
		    // 根据cust_account查询账号信息
		    AccountBean accountBean = accountExtendService.queryAccountDetailByCustAccount(cust_account);
		    // 判断账号信息是否找到
		    if (accountBean != null) {
			// 验证秘钥信息
			if (checkValidityService.toolsCheckSign(cust_account, accountBean.getKey_private(), timestamp, sign)) {
			    // //获取语音短信能力类型标识
			    SimpleDateFormat sdfMonth = new SimpleDateFormat("yyyyMM");
			    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
			    String fileName = null;
			    // 拼写目录名称
			    String monthStr = sdfMonth.format(new Date()) + "/";
			    fileName = sdf.format(new Date()) + ((int) (Math.random() * 9000) + 1000);// 上传,调接口的名字
			    // 获取项目绝对路径
			    String dpath = this.getRequest().getSession().getServletContext().getRealPath("../");
			    // 将各个账号的录音信息存放在相应账号的目录下
			    dpath = dpath + "/upload_voice/" + cust_account + "/" + monthStr;
			    // 创建文件夹
			    File fdir = new File(dpath);
			    if (!fdir.exists()) {
				fdir.mkdirs();
			    }
			    ResponseSendVoiceBean bean = YonYouUtil.textToSpeech(content.replaceAll("\r|\n|\t", ""));
			    if (bean.getResult().equals("0")) {
				try {

				    object = audeoNoticeService.uploadFile(app_key, cust_account, dpath + "/" + fileName, fileName + ".wav", content, bean.getFileName());
				    if ("0".equals(object.optString("result"))) {
					object.put("downUrl", bean.getDownUrl());
					object.put("describe", "文字转换语音文件成功");
				    }
				} catch (Exception e) {
				    log.error("文件上传失败", e);
				}
			    } else {
				object.put("result", "-1");
				object.put("describe", "转换语音失败");
				object.put("code", "0507");
				object.put("errorMsg", bean.getDesc());
			    }

			} else {
			    object.put("result", "-1");
			    object.put("describe", "参数sign错误");
			    object.put("code", "0001");
			}
		    } else {
			object.put("result", "-1");
			object.put("describe", "计费账号不存在");
			object.put("code", "0002");
		    }
		} else {
		    object.put("result", "-1");
		    object.put("describe", "请使用正确的应用标识");
		    object.put("code", "0007");
		}
	    }
	} catch (Exception e) {
	    e.printStackTrace();
	    log.info("********上传文字语音短信失败**********" + e);
	    object = new JSONObject();
	    object.put("result", "-1");
	    object.put("describe", "语音通知异常");
	    object.put("errorMsg", e.getMessage());
	    object.put("code", "0501");
	}

	/* 兼容老接口增加两个参数 */

	object.put("voice_id", "");

	// 计算结束时间
	double end = Calendar.getInstance().getTimeInMillis();
	// 计算发起接口道调用完毕所用的时间
	double during = Double.valueOf((end - begin)) / 1000;
	// 拼写写入日志内容
	String request_msg = "ext_terminalCode:" + ext_terminalCode + "|app_key:" + app_key + "|cust_account:" + cust_account + "|timestamp:" + timestamp + "|sign:" + sign
		+ "|content:" + content;
	this.logService.logInterface(during, "uploadVoiceNoticeV4", request_msg.length() > 500 ? request_msg.substring(0, 500) : request_msg,
		object.toString().length() > 200 ? object.toString().substring(0, 200) : object.toString(), object.getString("result").length() > 200 ? object.getString("result")
			.substring(0, 200) : object.getString("result"), DateUtils.getCurrentTime(), this.getRequest().getRemoteAddr(), "");

	String data = "";
	object.remove("errorMsg");
	if (StringUtils.isNotBlank(callback)) {
	    data = callback + "(" + object.toString() + ")";
	} else {
	    data = object.toString();
	}
	return returnData(data);
    }

}
